package com.rs.portal.reserve;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jaxplat.JaxplatBean;
import com.jaxplat.commons.Row;
import com.jaxplat.commons.RowImpl;
import com.rs.commons.ApplyType;
import com.rs.commons.RsErrCode;
import com.rs.rsbiz.reserve.delegate.ReserveOrderDelegate;
import com.rs.util.OrderAndSnid;
import com.rs.util.RegexUtil;
import com.rs.util.ServletUtil;

public class MPayCallbackServlet extends HttpServlet
{
    private Log log = LogFactory.getLog(MPayCallbackServlet.class);
    private static final long serialVersionUID = 4807763850518144181L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        // this.watch(request);

        Row params = null;
        try
        {
            params = ServletUtil.parseRequestParametersToRow(request);
        }
        catch (Exception e)
        {
            log.error(e);
        }
        String state = params.getString("state");
        String note = params.getString("note");
        String returnCode = params.getString("returnCode");
        
        String type = params.getString("type");
        String amount = params.getString("amount");
        String banks = params.getString("banks");
        String contractName = params.getString("contractName");
        String invoiceTitle = params.getString("invoiceTitle");
        String mobile = params.getString("mobile");
        String payDate = params.getString("payDate");
        String reserved = params.getString("reserved");
        String status = params.getString("status");
        String mac = params.getString("mac");
        
        String snid = params.getString("orderId");
        String message = params.getString("message");
        message = new String(message.getBytes("ISO-8859-1"), "UTF-8");

        StringBuffer sbMsg = new StringBuffer();
        for (Iterator it = params.entrySet().iterator(); it.hasNext();)
        {
            Map.Entry entry = (Map.Entry) it.next();
            String mkey = entry.getKey().toString();
            String mvalue = entry.getValue().toString();
            sbMsg.append(mkey + ": " + mvalue + "\n");
        }
        log.info("QueryString: " + request.getQueryString());

        log.info("支付结果回调信息: " + sbMsg.toString());
        Row callbackResult = new RowImpl();

        Row updateResult = new RowImpl();
        Row mpayInfo = null;
        if ("E00".equalsIgnoreCase(params.getString("state")))
        {
            // String orderId = OrderAndSnid.snidToOrderID(snid);
            log.info("手机支付结果通知:支付成功.[snid=" + snid + "]");
            ReserveOrderDelegate reserveorderDelegate = (ReserveOrderDelegate) JaxplatBean.getBean("reserveOrderDelegate");
            if (RegexUtil.test("^(" + OrderAndSnid.getSubMerId() + ")\\d{12}", snid))
            {
                mpayInfo = reserveorderDelegate.getMpayInfo(snid);
                if (null != mpayInfo)
                {

                    updateResult = reserveorderDelegate.udpateReservePayCallback(mpayInfo);
                    if ("0".equals(updateResult.getString("errcode")))
                    {

                        log.info("支付成功.[订单号： + " + updateResult.getString("order_id") + "支付流水号: " + snid + "]");
                        callbackResult.put("errcode", RsErrCode.SUCCESS);
                        callbackResult.put("message", "支付成功.[订单号: " + updateResult.getString("order_id") + "]");
                        callbackResult.put("order_id", updateResult.getString("order_id"));

                    }
                    else
                    {
                        callbackResult.putAll(updateResult);
                        log.info("手机支付失败.支付流水号[" + snid + "]. message: " + updateResult.getString("message"));
                    }
                }
                else
                {
                    log.info("手机支付失败:无效订单号.支付流水号[" + snid + "]");
                    callbackResult.put("errcode", RsErrCode.FAILED);
                    callbackResult.put("message", "手机支付结果通知:无效订单号.支付流水号[" + snid + "]");

                }
            }
            else
            {
                callbackResult.put("errcode", RsErrCode.FAILED);
                callbackResult.put("message", "手机支付结果通知:无效订单号.支付流水号[" + snid + "]");
                log.info("手机支付失败:无效订单号.支付流水号[" + snid + "]");
            }
        }
        else
        {
            callbackResult.put("errcode", RsErrCode.FAILED);
            callbackResult.put("message", "手机支付结果通知:无效订单号.支付流水号[" + snid + "]");
            log.info("手机支付失败:无效订单号.支付流水号[" + snid + "]");
        }

        try
        {
            // Row mpayInfo = (Row) updateResult.get("mpayInfo");

            if (null != mpayInfo)
            {
                String authorizeMode = mpayInfo.getString("AUTHORIZEMODE");
                if (RsErrCode.SUCCESS.equals(callbackResult.getString("errcode")))
                {

                    String redirectUrl = "";
                    if (ApplyType.WEB.equalsIgnoreCase(authorizeMode))
                    {
                        redirectUrl = request.getContextPath() + "/web2/reserveManageAction.do?method=viewReserveOrder&orderId="
                                + mpayInfo.getString("order_id");

                    }
                    else if (ApplyType.WAP.equalsIgnoreCase(authorizeMode))
                    {
                        redirectUrl = request.getContextPath() + "/wap/reserveManageAction.do?method=viewReserveOrder&orderId="
                                + mpayInfo.getString("order_id");
                    }

                    response.sendRedirect(redirectUrl);
                }
                else
                {
                    if (ApplyType.WEB.equalsIgnoreCase(authorizeMode))
                    {
                        request.setAttribute("message", "手机支付失败.支付流水号[" + snid + "]");
                        request.getRequestDispatcher("/web2/error.jsp").forward(request, response);
                    }
                    else
                    {
                        request.setAttribute("message", "手机支付失败.支付流水号[" + snid + "]");
                        request.getRequestDispatcher("/wap/error.jsp").forward(request, response);
                    }

                }
            }
            else
            {
                response.getWriter().println("无效请求，此系统是挂号系统，系方面百姓看病，请方面大家，谢谢！");
            }
        }
        catch (Exception e)
        {
            log.error("", e);
        }

    }

}
